﻿using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using B.S.RbacData.Write.API.Applications.Commands.Traceabilitys;
using B.S.RbacData.Write.API.Applications.Commands.Traceabilitys.DeepProcessings;
using B.S.RbacData.Write.API.Applications.Commands.Traceabilitys.Farmings;
using B.S.RbacData.Write.API.Applications.Commands.Traceabilitys.Slaughters;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace B.S.RbacData.Write.API.Controllers
{
    /// <summary>
    /// 溯源管理（写）
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class TraceabilityMenganmentController : ControllerBase
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<TraceabilityMenganmentController> logger;
        /// <summary>
        /// 中介者
        /// </summary>
        private readonly IMediator mediator;
        private readonly DataDbcontext _dbContext;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="logger">日志</param>
        /// <param name="mediator">中介者</param>
        public TraceabilityMenganmentController(ILogger<TraceabilityMenganmentController> logger, IMediator mediator, DataDbcontext dbContext)
        {
            this.logger = logger;
            this.mediator = mediator;
            this._dbContext = dbContext;
        }

        /// <summary>
        /// 添加产品信息
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回任务</returns>
        [HttpPost]
        public async Task<ApiResult<int>> AddProduct(AddProductCommand command)
        {

            try
            {
                return await mediator.Send(command);

            }
            catch (Exception ex)
            {
                logger.LogError("添加异常处理" + ex.Message);
                throw;
            }
        }


        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file">参数</param>
        /// <returns>返回虚拟路径</returns>
        [HttpPost]
        public async Task<ApiResult<string>> UpFiles(IFormFile file)
        {

            try
            {
                UpFilesCommand command = new UpFilesCommand();
                command.file = file;
                return await mediator.Send(command);
            }
            catch (Exception ex)
            {
                logger.LogError("上传文件异常处理" + ex.Message);
                throw;
            }
        }


        /// <summary>
        /// 修改产品信息
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回任务</returns>
        [HttpPost]
        public async Task<ApiResult<int>> UpdateProduct(UpdateProductCommand command)
        {


            try
            {
                return await mediator.Send(command);
            }
            catch (Exception ex)
            {
                logger.LogError("修改产品信息异常处理" + ex.Message);
                throw;
            }
        }
       
        /// <summary>
        ///  批量删除产品信息
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回任务</returns>
        [HttpPost]
        public async Task<ApiResult<int>> IsDelRanger(RangerIsDelCommand command)
        {

            try
            {
                return await mediator.Send(command);
            }
            catch (Exception ex)
            {
                logger.LogError("逻辑删除产品信息异常处理" + ex.Message);
                throw;
            }

        }
        /// <summary>
        /// 添加图片路径
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回任务</returns>

        [HttpPost]
        public  async Task<ApiResult<int>> AddImgs(AddImgsCommand command)
        {


            try
            {
                return await mediator.Send(command);
            }
            catch (Exception ex)
            {
                logger.LogError("添加图片异常处理" + ex.Message);
                throw;
            }
        }

       /// <summary>
       /// 逻辑删除图片路径
       /// </summary>
       /// <param name="command">命令</param>
       /// <returns>返回任务</returns>
        [HttpPost]

        public async Task<ApiResult<int>> RemoveImgs(RemoveImgsCommand command)
        {

            try
            {
                return await mediator.Send(command);
            }
            catch (Exception ex)
            {
                logger.LogError("逻辑删除图片路径异常处理" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 添加养殖信息
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回任务</returns>
        [HttpPost]
        public async Task<ApiResult<int>> AddFarming(AddFarmingCommand command)
        {
            try
            {
                return await mediator.Send(command);
            }
            catch (Exception ex)
            {
                logger.LogError("添加养殖信息异常处理" + ex.Message);
                throw;
            }
        }
 

        /// <summary>
        /// 添加养殖保健信息
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回任务</returns>
        [HttpPost]
        public async Task<ApiResult<int>> AddFarmingHealth(AddFarmingHealthCommand command)
        {
            try
            {
                return await mediator.Send(command);
            }
            catch (Exception ex)
            {
                logger.LogError("添加保健信息异常处理" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 修改养殖保健信息
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回任务</returns>
        [HttpPost]
        public  async Task<ApiResult<int>> UpdateFarmingHealth([FromBody] UpdateFarmingHealthCommand command)
        {

            try
            {
                return await mediator.Send(command);
            }
            catch (Exception ex)
            {
                logger.LogError("修改保健信息异常处理" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 逻辑删除保健信息
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回任务</returns>
        [HttpPost]
        public async Task<ApiResult<int>> IsDelFarmingHealth(IsDelFarmingHealthCommand command)
        {
            try
            {
                return await mediator.Send(command);
            }
            catch (Exception ex)
            {
                logger.LogError("逻辑删除保健信息异常处理" + ex.Message);
                throw;
            }



        }

        /// <summary>
        /// 添加养殖企业信息
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回任务</returns>
        [HttpPost]
        public async Task<ApiResult<int>> AddFarmingCorporate([FromBody]AddFarmingCorporateCommand command)
        {
            try
            {

                return await mediator.Send(command);
            }
            catch (Exception ex)
            {
                logger.LogError("添加养殖企业信息异常处理" + ex.Message);
                throw;
            }
        }


       /// <summary>
       /// 添加屠宰信息
       /// </summary>
       /// <param name="command">命令</param>
       /// <returns>返回任务</returns>

        [HttpPost]
        public async Task<ApiResult<int>> AddSlaughter([FromBody]AddSlaughterCommand command)
        {

            try
            {
                return await mediator.Send(command);
            }
            catch (Exception ex)
            {

                logger.LogError("添加屠宰信息异常处理" + ex.Message);
                throw;
            }


        }

        /// <summary>
        /// 添加屠宰企业信息
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回任务</returns>

        [HttpPost]
        public async Task<ApiResult<int>> AddSlaughterCorporate([FromBody]AddSlaughterCorporateCommand command)
        {

            try
            {
                return await mediator.Send(command);
            }
            catch (Exception ex)
            {
                logger.LogError("添加屠宰企业信息异常处理" + ex.Message);
                throw;
            }
        }


        /// <summary>
        /// 添加深加工信息
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回任务</returns>

        [HttpPost]
        public async Task<ApiResult<int>> AddDeepProcessing([FromBody]AddDeepProcessingCommand command)
        {
            try
            {
                return await mediator.Send(command);
            }
            catch (Exception ex)
            {
                logger.LogError("添加深加工信息异常处理" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 添加深加工企业信息
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回任务</returns>

        [HttpPost]
        public async Task<ApiResult<int>> AddDeepProcessingCorporate([FromBody] AddDeepProcessingCorporateCommand command)
        {
            try
            {
                return await mediator.Send(command);
            }
            catch (Exception ex)
            {
                logger.LogError("添加深加工企业信息异常处理" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 添加供应商信息
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回任务</returns>

        [HttpPost]
        public async Task<ApiResult<int>> AddSupplier([FromBody] AddSupplierCommand command)
        {
            try
            {
                return await mediator.Send(command);
            }
            catch (Exception ex)
            {
                logger.LogError("添加供应商信息异常处理" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 生成溯源码QR码
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回生成的QR码唯一标识列表</returns>
        [HttpPost]
        public async Task<ApiResult<List<string>>> GenerateQRCode([FromBody] GenerateQRCodeCommand command)
        {
            try
            {
                return await mediator.Send(command);
            }
            catch (Exception ex)
            {
                logger.LogError("生成QR码异常处理" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 导出溯源码QR码
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回ZIP文件字节数组</returns>
        [HttpPost]
        public async Task<IActionResult> ExportQRCode([FromBody] ExportQRCodeCommand command)
        {
            try
            {
                var zipBytes = await mediator.Send(command);
                
                // 使用默认文件名
                string fileName = $"溯源码_{command.Quantity}个.zip";
                
                // 尝试获取产品信息用于文件命名
                try
                {
                    var product = await _dbContext.Products
                        .Include(p => p.Goods)
                        .FirstOrDefaultAsync(p => p.ID == command.ProductId && !p.IsDeleted);
                    
                    if (product != null && product.Goods != null)
                    {
                        fileName = $"{product.Goods.GoodsName}_溯源码_{command.Quantity}个.zip";
                    }
                }
                catch
                {
                    // 如果获取产品信息失败，使用默认文件名
                }
                
                return File(zipBytes, "application/zip", fileName);
            }
            catch (Exception ex)
            {
                logger.LogError("导出QR码异常处理" + ex.Message);
                throw;
            }
        }
    }
}
